--[[
   @classmod Cursor
]]

local lume = @@lib (lume)

return Class {
   _name = "Cursor", 
   init = function (self, s)
      self.x, self.y = $LM.getPosition()
      self.rx, self.ry = 0, 0
      self.dx = 0
      self.dy = 0
      self.w = s
      self.h = s
      self.show = true
      self.color = {.1, .1, .1}
      self.grid = _src("grid")(8)
      self.selected = 1
   end,

   hide = function (self, v)
      self.show = v and nil or (not v and true)
   end,

   is_in_rect = function (self, x, y, w, h)
      local mx, my = self:get_position()
      return mx >= x and mx <= x + w-8 and
	 my >= y and my <= y + h-8
   end,

   moved = function (self)
      return @@ALL({self.dx, self.old_dx, self.dy, self.old_dy}, v == 0)
   end,

   update = function (self)
      self.is_hovering = nil
      self.grid:update()
      local rx, ry = _lm.getPosition()
      self.rx, self.ry = rx, ry
      
      local mx, my = Game.current_screen:to_local($LM.getPosition())
      mx, my = self.grid:snap(mx, my)
      self.x, self.y = mx, my
      self.ox, self.oy = self.ox or rx, self.oy or ry
      self.dx, self.dy = self.ox- rx, self.oy - ry
      self.x, self.y = mx, my
      self.ox, self.oy = rx, ry
      self.old_dx, self.old_dy = self:get_delta()
   end,

   draw = function (self)
      if not self.show or self.is_hovering then return end
      @@RECT(self.x, self.y, self.w, self.h, nil, #FFFFFF)
   end,

   get_position = function (self)
      return self.x, self.y
   end,

   get_scr_position = function (self)
      return $LM.getPosition()
   end,

   get_delta = function (self)
      return self.dx, self.dy
   end,

   clear_selection = function (self)
      if Game then Game.current_tile = nil end
      self.grid.tx, self.grid.ty = nil, nil
   end,
}
